<template>
  <div class="relative w-full h-full bg-white">
    <div class="p-30">
      <div class="w-120 m-auto">
        <p class="fs-30 text-red p-t-50">保银尊享</p>
        <p class="text-right fs-12 text-grey">经销商端</p>
      </div>
      <div class="m-t-50">
        <van-field
          v-model="username"
          class="flex a-center b-b"
          placeholder="手机号"
          label="账号"
          clearable
          left-icon="contact"
        />
        <van-field
          v-model="password"
          class="flex a-center b-b"
          label="密码"
          type="password"
          clearable
          placeholder="请输入密码"
        >
          <svg-icon slot="left-icon" name="lock" />
        </van-field>
        <van-button
          :loading="loading"
          loading-text="正在登录"
          @click="handleLogin()"
          class="w-full m-t-30 bg-red text-white b-none b-r-30"
        >登录</van-button>
        <p class="flex j-end p-10 p-t-20">
          <router-link to="/reset" class="text-grey fs-12">忘记密码?</router-link>
        </p>
      </div>
    </div>
    <div class="absolute bottom-0 left-0 w-full text-center p-20">
      <p class="text-grey fs-12">版本: v1.0.1</p>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  data () {
    return {
      loading: false,
      username: 'sysadmin',
      password: 'sysadmin'
    }
  },
  methods: {
    ...mapMutations(['changeLoginStatus', 'changeUser']),
    async handleLogin () {
      if (this.username && this.password) {
        this.loading = true
        let { status, message, token, user } = await this.$api.post('/login', {
          username: this.username,
          password: this.password
        })
        this.loading = false
        if (status === 0) {
          // 向Vuex添加用户登录态、用户信息
          this.changeLoginStatus(true)
          this.changeUser(user)
          // 向axios headers添加token
          this.$api.$axios.defaults.headers.common['token'] = token
          // localStorage 添加
          setItem('userInfo', JSON.stringify({ token, user }))
          this.$router.push('/')
        } else {
          this.changeLoginStatus(false)
          this.$toast(message)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.b-r-30 {
  border-radius: 30px;
}
</style>
